<template>
  <div style="position: relative; width: 100%; height: 100vh; background: skyblue;">
    <div style="border: 3px solid rgb(20, 39, 124); position: absolute; transform: translate(-50%, -50%); top: 50%; left: 50%; background: #fff; padding: 25px; border-radius: 15px;">
      <table id="login-table">
        <th colspan="2">使用账户名和密码登录</th>
        <tr>
          <td>账户名</td>
          <input style="border: 1px solid rgb(20, 39, 124);" placeholder="请输入账户名" type="text" v-model="Username"/>
        </tr>
        <tr>
          <td></td>
          <td id="tips-for-username" class="tips"></td>
        </tr>
        <tr>
          <td>密码</td>
          <input style="border: 1px solid rgb(20, 39, 124);" placeholder="请输入密码" type="password" v-model="Password"/>
        </tr>
        <tr>
          <td></td>
          <td id="tips-for-password" class="tips"></td>
        </tr>
        <tr>
          <td colspan="2" class="target-button button" @click="login" type="submit">登录</td>
        </tr>
        <tr>
          <td colspan="2" class="change-table button" @click="changeTable">没有账号？去注册一个新的</td>
        </tr>
      </table>
      <table id="register-table">
        <th colspan="2">使用账户名和密码注册</th>
        <tr>
          <td>账户名</td>
          <input style="border: 1px solid rgb(20, 39, 124);" placeholder="请输入账户名" type="text" v-model="uname"/>
        </tr>
        <tr>
          <td></td>
          <td id="tips-for-uname" class="tips"></td>
        </tr>
        <tr>
          <td>设置密码</td>
          <input style="border: 1px solid rgb(20, 39, 124);" placeholder="请输入密码" type="password" v-model="upass"/>
        </tr>
        <tr>
          <td></td>
          <td id="tips-for-upass" class="tips"></td>
        </tr>
        <tr>
          <td>确认密码</td>
          <input style="border: 1px solid rgb(20, 39, 124);" placeholder="请再次输入密码" type="password" v-model="usure"/>
        </tr>
        <tr>
          <td></td>
          <td id="tips-for-usure" class="tips"></td>
        </tr>
        <tr>
          <td colspan="2" class="target-button button" @click="register" type="submit">注册</td>
        </tr>
        <tr>
          <td colspan="2" class="change-table button" @click="changeTable">已有账号？去登录</td>
        </tr>
      </table>
      <div id="float-window" style="visibility: hidden;"></div>
    </div>
  </div>
</template>

<script>
// import bcrypt from 'bcryptjs'
import axios from 'axios'

function floatWindowClear() {
  const floatWindow = document.getElementById('float-window')
  floatWindow.style.visibility = 'hidden'
  floatWindow.innerText = ''
  floatWindow.innerHTML = ''
}
function floatWindowLoading() {
  floatWindowClear()
  const floatWindow = document.getElementById('float-window')
  floatWindow.innerHTML = '<div class="loading"><span></span></div>'
  floatWindow.style.visibility = 'visible'
}
function floatWindowAlert(text, time) {
  floatWindowClear()
  const floatWindow = document.getElementById('float-window')
  floatWindow.innerText = text
  floatWindow.style.visibility = 'visible'
  setTimeout(() => { floatWindowClear() }, time)
}

var displayOne = ['', 'none']
var displaySeq = 0
function changeTableDisplay() {
  document.getElementById('login-table').style.display = displayOne[displaySeq % 2]
  document.getElementById('register-table').style.display = displayOne[(displaySeq + 1) % 2]
  displaySeq += 1
}

function checkInput(input, tipsElemId, tipsText) {
  let isEmpty = (input === '')
  document.getElementById(tipsElemId).innerText = isEmpty ? tipsText : ''
  return isEmpty
}

export default {
  name: 'Login',
  data(){
    return {
      salt: 11,
      Username: '',
      Password: '',
      uname: '',
      upass: '',
      usure: ''
    }
  },
  methods: {
    getInfo: function() {
      return axios({
        method: 'get',
        url: this.globalData.apiURL + '/User/UserInfo',
        headers: {
          'Authorization': this.globalData.User.Token
        }
      })
        .then((res) => {
          console.log(res.data)
          if(res.data.code === 0){
            let info = res.data.data
            this.globalData.User.Id = info.id
            this.globalData.User.Username = info.username
            this.globalData.User.Nickname = info.Nickname
            this.globalData.User.Email = info.Email
            if(info.userPic === null) {
              this.globalData.User.User_pic = ''
            } else {
              this.globalData.User.User_pic = info.userPic
            }
            this.globalData.User.CreateDate = info.createTime
            this.globalData.User.UpdateDate = info.updateTime
            localStorage.setItem('UserJSON', JSON.stringify(this.globalData.User))
          } else {
            window.alert(res.data.message)
          }
        })
        .catch((error) => {
          console.log(error)
          console.log('查询用户详情出错了')
        })
    },
    checkPassword: function(psw, con) {
      if(psw.length < 8) {
        return [false, '密码长度不得小于8位']
      } else if (psw.length > 24) {
        return [false, '密码长度不得大于24位']
      } else if (/[^0-9a-zA-Z.*-_#]/.test(psw)) {
        return [false, '密码中不得包含除字母、数字、点号"."、星号"*"、井号"#"、短横线"-"、下划线"_"以外的字符']
      } else if(psw !== con){
        return [false, '两次输入密码不一致']
      } else return [true, 'pass']
    },
    checkUsername: function(username) {
      if(/\s/.test(username)) {
        return [false, '用户名中不得包含空字符']
      } else if(!/\S{5,}/.test(username)) {
        return [false, '用户名长度不得小于5']
      } else {
        return [true, 'pass']
      }
    },
    login() {
      let usernameIsEmpty = checkInput(this.Username, 'tips-for-username', '请输入账户名！')
      let passwordIsEmpty = checkInput(this.Password, 'tips-for-password', '请输入密码！')
      if(usernameIsEmpty || passwordIsEmpty){
        return
      }
      let nameInfo = this.checkUsername(this.username)
      if(nameInfo[0] === false){
        floatWindowAlert(nameInfo[1], 3000)
        return
      }
      floatWindowLoading()
      let formData = new FormData()
      formData.append('Username', this.Username)
      formData.append('Password', this.Password)
      axios({
        method: 'post',
        url: this.globalData.apiURL + '/User/Login',
        data: formData
      })
        .then(res => {
          if(res.data.code === 0) { // 登录成功
            console.log('success')
            this.globalData.User.Username = this.Username
            this.globalData.User.Token = res.data.data // JWT令牌
            this.getInfo().then(res => {
              this.$router.push({name: 'Home'}) // 回到来时的页面
            })
            /* 跳转、获取信息等 */
          } else { // 登录失败
            this.Password = ''
            floatWindowAlert(res.data.message, 3000)
          }
        })
        .catch((error) => { // 接口请求失败
          floatWindowAlert('服务器或网络错误', 3000)
          console.log(error);
        });
    },
    register() {
      let usernameIsEmpty = checkInput(this.uname, 'tips-for-uname', '请输入用户名！')
      let passwordIsEmpty = checkInput(this.upass, 'tips-for-upass', '请设置账户密码！')
      let ensuranceIsEmpty = checkInput(this.usure, 'tips-for-usure', '请再次输入密码!')
      if(usernameIsEmpty || passwordIsEmpty || ensuranceIsEmpty){
        return
      }
      let passInfo = this.checkPassword(this.upass, this.usure)
      if(passInfo[0] === false){
        floatWindowAlert(passInfo[1], 3000)
        return
      }
      let nameInfo = this.checkUsername(this.uname)
      if(nameInfo[0] === false){
        floatWindowAlert(nameInfo[1], 3000)
        return
      }
      floatWindowLoading()
      let formData = new FormData()
      formData.append('Username', this.uname)
      formData.append('Password', this.upass)
      axios({
        method: 'post',
        url: this.globalData.apiURL + '/User/Register',
        data: formData
      })
        .then((res) => {
          console.log(res)
          if(res.data.code === 0) { // 注册成功
            console.log('success')
            /* 跳转、获取信息等 */
            floatWindowAlert('注册成功！\n点击登录吧！', 3000)
            this.changeTable()
          } else { // 注册失败
            floatWindowAlert(res.data.message, 3000)
          }
        })
        .catch((error) => { // 接口请求失败
          floatWindowAlert('服务器或网络错误', 3000)
          console.log(error);
        })
    },
    changeTable() {
      changeTableDisplay()
    }
  },
  mounted() {
    changeTableDisplay()
  }
}
</script>

<style>
#login-table {
  margin: auto;
  vertical-align: middle;
  text-align: center;
}
#register-table {
  margin: auto;
  vertical-align: middle;
  text-align: center;
}
.tips {
  font-family: KaiTi;
  font-size:  small;
  color: red;
}
.button {
  user-select:none;
}
.target-button {
  margin: auto;
  text-align: center;
  background-color: rgb(20, 39, 124);
  color: #fff;
  font-weight: 900;
  box-shadow: 3px 0 0 3px var(--primary-color);
}
.target-button:active {
  box-shadow: currentColor;
  transition-duration: 0.2s;
}
.change-table {
  color:rgb(8, 0, 128);
  font-size: small;
}
#float-window {
  height: 50px;
  margin: 0 auto;
  font-size: large;
  font-weight: 1200;
  color: rgba(2, 50, 81, 0.808);
  text-align: center;
  position: fixed;
  left: 50%;
  float: right;
  transform: translateX(-50%);
}
.loading {
  text-align: center;
  vertical-align: auto;
}
.loading>span {
  animation: loading 1000ms infinite linear;
  border-radius: 100%;
  border: 6px solid #2d61bb;
  border-left-color: transparent;
  color: transparent;
  display: inline-block;
  line-height: 1.2;
  width: 50px;
  height: 50px;
}
@keyframes loading {
  0% { transform: rotate(0deg);}
  100% { transform: rotate(360deg);}
}

</style>
